package com.ktjiaoyu.ktmall.servlet.admin;

import com.alibaba.fastjson.JSON;
import com.ktjiaoyu.ktmall.entity.Product;
import com.ktjiaoyu.ktmall.service.ProductService;
import com.ktjiaoyu.ktmall.service.impl.ProductServiceImpl;
import com.ktjiaoyu.ktmall.utils.R;
import com.ktjiaoyu.ktmall.utils.RequestUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xm
 * @date 2025/9/15
 * @Dome
 */
@WebServlet(name = "ProductServlet", urlPatterns = "/api/product/*")
public class ProductServlet extends HttpServlet {
    private final ProductService productService = new ProductServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        String path = req.getPathInfo();
        PrintWriter out = resp.getWriter();
        R result;
        if (path == null || "/list".equals(path)) {
            String title = req.getParameter("title");
            Long categoryId = RequestUtil.parseLong(req, "category_id", null);
            int page = RequestUtil.parseInt(req, "page", 1);
            int pageSize = RequestUtil.parseInt(req, "pageSize", 10);
            List<Product> list = productService.findList(title, categoryId, page, pageSize);
            int total = productService.count(title, categoryId);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("list", list);
            data.put("total", total);
            result = R.ok(data);
        } else if (path.matches("/\\d+")) {
            Long id = Long.valueOf(path.substring(1));
            Product product = productService.findById(id);
            result = product != null ? R.ok(product) : R.fail("商品不存在");
        } else {
            result = R.fail("无效的请求路径");
        }
        out.print(JSON.toJSONString(result));
        out.flush();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        BufferedReader br = req.getReader();
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        Product product = JSON.parseObject(sb.toString(), Product.class);
        System.out.println("接收到的商品数据: " + product);
        if (product.getMain_image() == null) {
            product.setMain_image("");
        }
        if (product.getImages() == null) {
            product.setImages("");
        }
        boolean success = productService.saveProduct(product);
        R result = success ? R.ok() : R.fail("保存失败");
        PrintWriter out = resp.getWriter();
        out.print(JSON.toJSONString(result));
        out.flush();
        out.close();
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        String path = req.getPathInfo();
        PrintWriter out = resp.getWriter();
        if (path != null && path.matches("/\\d+")) {
            Long id = Long.valueOf(path.substring(1));
            boolean success = productService.removeById(id);
            R result = success ? R.ok() : R.fail("删除失败");
            out.print(JSON.toJSONString(result));
        } else {
            out.print(JSON.toJSONString(R.fail("无效的请求路径")));
        }
        out.flush();
        out.close();
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        String path = req.getPathInfo();
        PrintWriter out = resp.getWriter();
        if (path != null && path.matches("/\\d+/status")) {
            Long id = Long.valueOf(path.split("/")[1]);
            BufferedReader reader = req.getReader();
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Map<String, Object> map = JSON.parseObject(sb.toString(), Map.class);
            Integer status = (Integer) map.get("status");
            boolean success = productService.updateStatus(id, status);
            R result = success ? R.ok() : R.fail("状态更新失败");
            out.print(JSON.toJSONString(result));
        } else {
            out.print(JSON.toJSONString(R.fail("无效的请求路径")));
        }
        out.flush();
        out.close();
    }
}
